package com.xuzao.developer.utils;


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

/**
 * excel操作工具类
 *
 * @author wangyt
 * @version 1.0 created 2018/8/24
 */
public class ExcelUtils {

    /**
     * 错误信息接受器
     */
    private static String errorMsg;

    /**
     * 设置最大列字符数
     */
    private static Integer MAX_COLUMN_WIDTH = 26624;

    /**
     * 构造方法
     */
    public ExcelUtils() {
    }

    /**
     * 获取错误信息
     *
     * @return str
     */
    public String getErrorInfo() {
        return errorMsg;
    }

    /**
     * 读EXCEL文件，获取信息集合
     *
     * @param mFile 文件名称
     * @return list
     */
    public static Workbook getExcelInfo(MultipartFile mFile) {
        // 获取文件名
        String fileName = mFile.getOriginalFilename();
        try {
            // 验证文件名是否合格
            if (!validateExcel(fileName)) {
                return null;
            }
            // 根据文件名判断文件是2003版本还是2007版本
            boolean isExcel2003 = true;
            if (isExcel2007(fileName)) {
                isExcel2003 = false;
            }
            return getWorkbook(mFile.getInputStream(), isExcel2003);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据excel里面的内容读取客户信息
     *
     * @param is          输入流
     * @param isExcel2003 excel是2003还是2007版本
     * @return list
     */
    private static Workbook getWorkbook(InputStream is, boolean isExcel2003) {
        try {
            Workbook wb;
            // 当excel是2003时,创建excel2003
            if (isExcel2003) {
                wb = new HSSFWorkbook(is);
                // 当excel是2007时,创建excel2007
            } else {
                wb = new XSSFWorkbook(is);
            }
            return wb;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 验证EXCEL文件
     *
     * @param filePath 文件路径
     * @return boolean
     */
    private static boolean validateExcel(String filePath) {
        boolean excel2003, excel2007;
        excel2003 = isExcel2003(filePath);
        excel2007 = isExcel2007(filePath);
        if (!(excel2003 || excel2007)) {
            errorMsg = "文件名不是excel格式";
            return false;
        } else if (StringUtils.isBlank(filePath)) {
            errorMsg = "文件名不是excel格式";
            return false;
        }
        return true;
    }

    /**
     * 是否是2003的excel，返回true是2003
     *
     * @param filePath 文件路径
     * @return boolean
     */
    private static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    /**
     * 是否是2007的excel，返回true是2007
     *
     * @param filePath 文件路径
     * @return boolean
     */
    private static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }


    public static void export(String title, String[] rowName, List<Object[]> dataList, HttpServletResponse response) {
        export(title, null, rowName, dataList, response, null, null, null, true);
    }

    public static void export(String title, String[] rowName, List<Object[]> dataList, HSSFCellStyle titleStyle, HSSFCellStyle cellStyle, HSSFWorkbook workbook, HttpServletResponse response) {
        export(title, null, rowName, dataList, response, titleStyle, cellStyle, workbook, false);
    }

    public static void export(String title, String fileName, String[] rowName, List<Object[]> dataList, HttpServletResponse response) {
        export(title, fileName, rowName, dataList, response, null, null, null, true);
    }

    /**
     * 导出数据
     *
     * @param title         标题
     * @param rowName       列名数组
     * @param dataList      数据列
     * @param response      http应答类
     * @param titleStyle    标题样式
     * @param cellStyle     单元格样式
     * @param isCreateTitle 是否创建标题
     * @author wangyt created 2018/8/27
     */
    public static void export(String title, String fileName, String[] rowName, List<Object[]> dataList, HttpServletResponse response, HSSFCellStyle titleStyle, HSSFCellStyle cellStyle, HSSFWorkbook workbook, Boolean isCreateTitle) {
        try {
            // 创建工作簿对象
            if (null == workbook) {
                workbook = new HSSFWorkbook();
            }
            // 创建工作表
            HSSFSheet sheet = workbook.createSheet(title);
            sheet.setDefaultColumnWidth(5);
            // 产生表格标题行
            HSSFRow rowm = sheet.createRow(0);


            //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面  - 可扩展】
            //获取列头样式对象
            HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);

            if (null != titleStyle) {
                columnTopStyle = titleStyle;
            }


            //单元格样式对象
            HSSFCellStyle style = getStyle(workbook);
            if (cellStyle != null) {
                style = cellStyle;
            }

            HSSFRow rowRowName;

            if (isCreateTitle) {
                sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
                HSSFCell cellTiltle = rowm.createCell(0);
                cellTiltle.setCellStyle(columnTopStyle);
                cellTiltle.setCellValue(title);
                rowRowName = sheet.createRow(2);
            } else {
                rowRowName = sheet.createRow(0);
            }
            // 定义所需列数
            int columnNum = rowName.length;
            // 在索引2的位置创建行(最顶端的行开始的第二行)


            // 将列头设置到sheet的单元格中
            for (int n = 0; n < columnNum; n++) {
                //创建列头对应个数的单元格
                HSSFCell cellRowName = rowRowName.createCell(n);
                //设置列头单元格的数据类型
                cellRowName.setCellType(CellType.STRING);
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                //设置列头单元格的值
                cellRowName.setCellValue(text);
                //设置列头单元格样式
                cellRowName.setCellStyle(columnTopStyle);
            }

            //将查询出的数据设置到sheet对应的单元格中
            for (int i = 0; i < dataList.size(); i++) {
                //遍历每个对象
                Object[] obj = dataList.get(i);
                //创建所需的行数
                HSSFRow row = sheet.createRow(isCreateTitle ? i + 3 : i+1);

                for (int j = 0; j < obj.length; j++) {
                    //设置单元格的数据类型
                    HSSFCell cell;
                    cell = row.createCell(j, CellType.STRING);
                    //设置单元格的值
                    cell.setCellValue("");
                    if (!"".equals(obj[j]) && obj[j] != null) {
                        String value = "";
                        if (obj[j] instanceof Date) {
                            // 如果是时间类型的 转成String类型
                            value = DateUtil.format((Date) obj[j]);
                        } else if (obj[j] instanceof BigDecimal) {
                            // 如果是金额类型，末尾去除零
                            value = ((BigDecimal) obj[j]).stripTrailingZeros().toPlainString();
                        } else {
                            value = obj[j].toString();
                        }
                        cell.setCellValue(value);
                    }
                    //设置单元格样式
                    cell.setCellStyle(style);
                }
            }
            //让列宽随着导出的列长自动适应
            for (int colNum = 0; colNum < columnNum; colNum++) {
                int columnWidth = sheet.getColumnWidth(colNum) / 256;
                for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                    HSSFRow currentRow;
                    //当前行未被使用过
                    if (sheet.getRow(rowNum) == null) {
                        currentRow = sheet.createRow(rowNum);
                    } else {
                        currentRow = sheet.getRow(rowNum);
                    }
                    if (currentRow.getCell(colNum) != null) {
                        HSSFCell currentCell = currentRow.getCell(colNum);
                        if (currentCell.getCellTypeEnum().equals(CellType.STRING)) {
                            int length = currentCell.getStringCellValue().getBytes().length;
                            if (columnWidth < length) {
                                columnWidth = length;
                            }
                        }
                    }
                }
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256 > MAX_COLUMN_WIDTH ? MAX_COLUMN_WIDTH : (columnWidth - 2) * 256);
                } else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256 > MAX_COLUMN_WIDTH ? MAX_COLUMN_WIDTH : (columnWidth + 4) * 256);
                }
            }

            if (workbook != null) {
                try {
                    if (StringUtils.isBlank(fileName)) {
                        fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13);
                    }
                    fileName = fileName + ".xls";
                    String headStr = "attachment; filename=\"" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1) + "\"";
                    response.setHeader("Content-Disposition", headStr);
                    response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                    response.setCharacterEncoding("UTF-8");
                    OutputStream out = response.getOutputStream();
                    workbook.write(out);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 列头单元格格式
     *
     * @param workbook 工作簿
     * @return HSSFCellStyle
     * @author wangyt created 2018/8/27
     */
    private static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 11);
        font.setBold(true);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;

    }

    /**
     * 列头单元格格式  工作计划导出样式
     *
     * @param workbook 工作簿
     * @return HSSFCellStyle
     * @author wangyt created 2018/8/27
     */
    public static HSSFCellStyle getTitleStyleForDevelop(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 10);
        font.setBold(true);
        //设置字体名字
        font.setFontName("微软雅黑");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        style.setFillBackgroundColor(IndexedColors.YELLOW.getIndex());
        return style;

    }


    /**
     * 列数据信息单元格样式
     *
     * @param workbook 工作簿
     * @return HSSFCellStyle
     * @author wangyt created 2018/8/27
     */
    private static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;

    }

    /**
     * 列数据信息单元格样式  开发进度统计
     *
     * @param workbook 工作簿
     * @return HSSFCellStyle
     * @author wangyt created 2018/8/27
     */
    public static HSSFCellStyle getCellStypeForDevelop(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体名字
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 9);
        font.setBold(false);
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getColor().getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(true);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.LEFT);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);

        return style;

    }
}
